package com.binguo.wxapi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binguo.common.enums.*;
import com.binguo.common.exception.ErrorCode;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.common.util.FileDownloader;
import com.binguo.common.util.Jpush.push.JPushUtil;
import com.binguo.common.util.LoggerUtil;
import com.binguo.common.util.UrlUtils;
import com.binguo.entity.DiscountOrderDetail;
import com.binguo.helper.FaceHelper;
import com.binguo.helper.FaceHelperV3;

import com.binguo.model.api.vo.OrderVO;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.model.repository.*;
import com.binguo.model.wxapi.form.*;
import com.binguo.model.wxapi.vo.*;

import com.binguo.model.wxapi.form.ApiGetSideBoardListForm;
import com.binguo.service.*;
import com.binguo.wxapi.baidu.BaiduRecUtil;


import com.binguo.wxapi.controller.ApiController;
import com.binguo.wxapi.form.ManKeBaoForm;
import com.binguo.wxapi.form.MeshProductOrderDetail;
import com.binguo.wxapi.form.api.ApiDeviceForm;
import com.binguo.wxapi.form.api.ApiPayForm;
import com.binguo.wxapi.form.openApiForm.ApiConfigForm;
import com.binguo.wxapi.form.openApiForm.ApiCustomerGroupCreateForm;
import com.binguo.wxapi.form.openApiForm.ApiCustomerGroupListForm;
import com.binguo.wxapi.transfer.OrderNoBuilder;
import com.binguo.wxapi.util.BarcodeUtil;

import com.binguo.wxapi.vo.ProductImgVO;
import com.binguo.wxapi.vo.api.ApiProductListVO;
import com.binguo.wxapi.vo.api.ApiProductVO;
import com.binguo.wxapi.vo.api.ApiUserListVO;
import com.binguo.wxapi.vo.api.CashierDeskVO;
import com.binguo.wxapi.vo.external.OrderForExternalVO;
import com.binguo.wxapi.vo.external.OrderItemForExternalVO;
import com.binguo.wxapi.vo.external.OrderResultVO;
import com.binguo.yprecapi.YpRecService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.File;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.binguo.common.exception.ErrorCode.PAYCARD_NOT_SUFFICIENT_FUNDS;
import static com.binguo.common.util.YPConstants.MD5;


@Service
public class ApiService implements InitializingBean {
    private static Logger logger = LoggerFactory.getLogger(ApiService.class);
    @Resource
    private PayCardMapper payCardMapper;


    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private ShopRepository shopRepository;

    @Autowired
    private FaceRepository faceRepository;

    @Autowired
    private LogAbcBankRechargeRepository logAbcBankRechargeRepository;

    @Resource
    private CustomerExtendMapper customerExtendMapper;

    @Resource
    private BinguoOrderMapper binguoOrderMapper;

    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private ProductRepository productRepository;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private BranchMapper branchMapper;
    @Resource
    private ProductCategoryRepository productCategoryRepository;
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private CashierDeskMapper cashierDeskMapper;
    @Resource
    private CashierDeskRepository cashierDeskRepository;
    @Resource
    private SideBoardMapper sideBoardMapper;
    @Resource
    private RequestApiRecordMapper requestApiRecordMapper;
    @Autowired
    private ShopChannelRepository shopChannelRepository;
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private CustomerService customerService;
    @Resource
    private ISqlService iSqlService;
    @Resource
    private BranchService branchService;
    @Resource
    private ProductService productService;
    @Resource
    private MdmsCTypeRepository mdmsCTypeRepository;
    @Resource
    private UploadFileService uploadFileService;
    @Resource
    private BowlService bowlService;
    @Resource
    private ShopService shopService;
    @Resource
    private ShopProductMsgService shopProductMsgService;
    @Resource
    private YpRecService ypRecService;
    @Resource
    private PayCardRepository payCardRepository;
    @Resource
    private YpCardService ypCardService;
    @Resource
    private OrderNoBuilder orderNoBuilder;
    @Resource
    private BinguoOrderRepository binguoOrderRepository;
    @Resource
    private WxDeleteProductService wxDeleteProductService;
    @Resource
    private NormalConfigMapper normalConfigMapper;
    @Resource
    private CustomerGroupRepository customerGroupRepository;
    @Resource
    private NewDiscountService newDiscountService;

    private Map<String, Shop> appIdShopMap;

    private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");



    public CashierDesk apiPayCashierDesk = null;

    public void addOrderPayCashierDesk(Shop shop){
        if (apiPayCashierDesk == null) {
            String cashierDeskName = "外部消费机";
            Condition cashierDeskCondition = new Condition(CashierDesk.class);
            cashierDeskCondition.or().andEqualTo("shopid", shop.getId())
                    .andEqualTo("name", cashierDeskName)
                    .andEqualTo("deleted", false)
            ;

            List<CashierDesk> cashierDeskList = cashierDeskMapper.selectByCondition(cashierDeskCondition);

            if (cashierDeskList != null && cashierDeskList.size() > 0) {
                apiPayCashierDesk = cashierDeskList.get(0);
            } else {
                Condition branchCondition = new Condition(Branch.class);
                branchCondition.or().andEqualTo("shopId", shop.getId())
                ;
                List<Branch> branchList = branchMapper.selectByCondition(branchCondition);

                apiPayCashierDesk = new CashierDesk();
                apiPayCashierDesk.setShopid(shop.getId());
                apiPayCashierDesk.setBranchid(branchList.get(0).getBranchId());
                apiPayCashierDesk.setCreated(new Date());
                apiPayCashierDesk.setDeleted(false);
                apiPayCashierDesk.setShopname(shop.getName());
                apiPayCashierDesk.setName(cashierDeskName);
                apiPayCashierDesk.setUpdated(apiPayCashierDesk.getCreated());
                cashierDeskRepository.save(apiPayCashierDesk);
            }
        }
    }

    public String orderPay(ApiPayForm form){
        Shop shop = appIdShopMap.get(form.getAppId());

        if (apiPayCashierDesk == null) {
            addOrderPayCashierDesk(shop);
        }

        Condition customerCondition = new Condition(Customer.class);
        customerCondition.setOrderByClause( " id limit 1");
        customerCondition.or().andEqualTo("phone", form.getCardNo());

        List<Customer> customerList = customerMapper.selectByCondition(customerCondition);

        Customer customer = null;

        if (customerList != null && customerList.size() > 0) {
            customer = customerList.get(0);
        }else {
            throw new ServiceException("用户不存在");
        }

        Condition payCardCondition = new Condition(PayCard.class);
        payCardCondition.or().andEqualTo("shopid", shop.getId())
                .andEqualTo("customerid", customer.getId())
                .andEqualTo("deleted", false)
        ;
        List<PayCard> payCardList = payCardMapper.selectByCondition(payCardCondition);

        PayCard payCard = null;
        if (payCardList != null && payCardList.size() > 0) {
            payCard = payCardList.get(0);
        }else {
            throw new ServiceException("用户卡不存在");
        }

        Condition customerExtendCondition = new Condition(CustomerExtend.class);
        customerExtendCondition.or()
                .andEqualTo("customerId", payCard.getCustomerid())
                .andEqualTo("shopId", shop.getId())
        ;

        List<CustomerExtend> customerExtendList = customerExtendMapper.selectByCondition(customerExtendCondition);

        Integer groupId = null;
        if (customerExtendList != null && customerExtendList.size() > 0) {
            CustomerExtend customerExtend = customerExtendList.get(0);
            groupId = customerExtend.getGroupId();
        }


        Long totalPrice = form.getAmount();

        if (totalPrice <= 0) {
            throw new ServiceException("金额错误");
        }

        String orderNo = "YP" + orderNoBuilder.createPlatformOrderNo();



        BinguoOrder binguoOrder = BinguoOrder.builder()
                .orderno(orderNo)
                .serial(form.getBizOrderNo())
                .serialnumber(form.getBizOrderNo())
                .cardid(payCard.getId())
                .cardno(payCard.getCardno())
                .cashierdeskid(apiPayCashierDesk.getId())
                .created(new Date())
                .customergroupid(groupId)
                .customerid(customer.getId())
                .customername(customer.getName())
                .customerphone(customer.getPhone())
                .totalfee(totalPrice)
                .realfee(totalPrice)
                .openid(customer.getOpenid())
                .ordertype(4)
                .paystatus(new Byte("1"))
                .refundfee(0L)
                .shopid(shop.getId())
                .source(PayType.CARDPAY.getCode().byteValue())
                .totalquantity(1)
                .branchid(apiPayCashierDesk.getBranchid())
                .build();

        DiscountOrderDetail discountOrder = null;

        if (groupId != null && groupId > 0 && totalPrice > 0) {
            discountOrder = newDiscountService.discount(shop.getId(), customer.getId(), totalPrice, groupId);

            if (discountOrder != null) {
                totalPrice = discountOrder.getTotalFee();

                binguoOrder.setRealfee(totalPrice);

            }
        }

        if (totalPrice > 0) {
            Long balance = payCard.getAccountbalance();
            Long wxBalance = payCard.getWxAccountbalance();
            Long yktBalance = payCard.getYktAccountbalance();
            Long bzBalance = payCard.getBzAccountbalance();

            Long bzNewBalance = bzBalance - totalPrice;
            Long yktNewBalance = yktBalance - totalPrice + bzBalance;
            Long newBalance = balance - totalPrice + yktBalance + bzBalance;
            Long wxNewBalance = wxBalance - totalPrice + balance + yktBalance + bzBalance;

            if (bzNewBalance >= 0) {
                PayCard tempPayCard = new PayCard();
                tempPayCard.setId(payCard.getId());
                tempPayCard.setBzAccountbalance(bzNewBalance);
                binguoOrder.setBzMoney(totalPrice);
                payCardMapper.updateByPrimaryKeySelective(tempPayCard);

            } else if (yktNewBalance >= 0) {
                PayCard tempPayCard = new PayCard();
                tempPayCard.setBzAccountbalance(0l);
                tempPayCard.setId(payCard.getId());
                tempPayCard.setYktAccountbalance(yktNewBalance);

                binguoOrder.setBzMoney(bzBalance);
                binguoOrder.setYktMoney(totalPrice - bzBalance);

                payCardMapper.updateByPrimaryKeySelective(tempPayCard);

            } else if (newBalance >= 0) {
                PayCard tempPayCard = new PayCard();
                tempPayCard.setBzAccountbalance(0l);
                tempPayCard.setYktAccountbalance(0l);
                tempPayCard.setId(payCard.getId());
                tempPayCard.setAccountbalance(newBalance);

                binguoOrder.setBzMoney(bzBalance);
                binguoOrder.setYktMoney(yktBalance);
                binguoOrder.setMoney(totalPrice - bzBalance - yktBalance);

                payCardMapper.updateByPrimaryKeySelective(tempPayCard);
            } else if (wxNewBalance >= 0) {
                PayCard tempPayCard = new PayCard();
                tempPayCard.setWxAccountbalance(wxNewBalance);
                tempPayCard.setYktAccountbalance(0l);
                tempPayCard.setAccountbalance(0l);
                tempPayCard.setBzAccountbalance(0l);
                tempPayCard.setId(payCard.getId());

                binguoOrder.setYktMoney(yktBalance);
                binguoOrder.setMoney(balance);
                binguoOrder.setBzMoney(bzBalance);
                binguoOrder.setWxMoney(totalPrice - bzBalance - yktBalance - balance);

                payCardMapper.updateByPrimaryKeySelective(tempPayCard);
            } else {
                throw new ServiceException(PAYCARD_NOT_SUFFICIENT_FUNDS);
            }
        }


        OrderItem orderItem = OrderItem.builder()
                        .orderno(orderNo)
                        .productid(5097)
                        .productname("外部消费")
                        .price(totalPrice)
                        .realprice(totalPrice)
                        .quantity(1)
                        .created(new Date())
                        .updated(new Date()).build();

        saveOrder(orderItem, binguoOrder);

        return orderNo;
    }

    @Transactional
    public void saveOrder(OrderItem orderItem, BinguoOrder binguoOrder){
        orderItemMapper.insertSelective(orderItem);
        binguoOrderMapper.insertSelective(binguoOrder);
    }

    public void delProduct(ApiDelProductForm form) {
        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        Condition productCondition = new Condition(Product.class);
        productCondition.or().andEqualTo("shopid", shop.getId())
                .andEqualTo("searchcode", form.getProductCode())
                .andEqualTo("deleted", false);

        Product product = productService.getProductBySearchCode(shop.getId(),form.getProductCode());

        if (product == null){
            throw new ServiceException("菜品不存在");
        }
        product.setDeleted(true);
        product.setUpdated(new Date());
        productRepository.update(product);

        wxDeleteProductService.doDeleteProduct(product);
        Product targetProduct = productService.getShopProductRefProductId(product.getId(), product.getShopid());

        if (targetProduct != null) {
            wxDeleteProductService.doDeleteProduct(targetProduct);
        }
        productService.addShopProductVersion(product.getShopid());

    }

    public Integer addProduct(ApiProductForm form) {
        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }


        Product product = productService.getProductBySearchCode(shop.getId(),form.getProductCode());

        if (product != null) {
            throw new ServiceException("该店铺下存在相同的ProductId");
        }else {
            ProductCategory category = productService.getProductCategory(shop.getId(),form.getCategoryName());
            //product.setMinorcategoryid(category.getId());

            Condition branchCondtion = new Condition(Branch.class);
            branchCondtion.or().andEqualTo("shopId", shop.getId())
                    .andEqualTo("branchId",form.getBranchId());
            List<Branch> branchList = branchMapper.selectByCondition(branchCondtion);

            if (branchList == null || branchList.size() == 0) {
                throw new ServiceException("该店铺下不存在此分店Id");
            }

            Product temp = new Product();
            temp.setName(form.getProductName());
            temp.setPrice(form.getPrice());
            temp.setProductpic(form.getProductImage());
            temp.setMinorcategoryid(category.getId());
            temp.setShopid(shop.getId());
            temp.setVipprice(form.getPrice());
            temp.setCreated(new Date());
            temp.setUpdated(temp.getCreated());
            temp.setSearchcode(form.getProductCode());
            temp.setDeleted(false);
            temp.setStatus(new Byte("1"));
            temp.setStoreid(form.getBranchId());
            productRepository.save(temp);

            return temp.getId();
        }
    }

    public void updateProduct(ApiProductForm form) {
        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        Product product = productService.getProductBySearchCode(shop.getId(),form.getProductCode());

        if (product == null){
            throw new ServiceException("菜品不存在");
        }

        if (!StringUtils.isEmpty(form.getProductName())){
            product.setName(form.getProductName());
        }
        if (!StringUtils.isEmpty(form.getCategoryName())){
            ProductCategory category = productService.getProductCategory(shop.getId(),form.getCategoryName());
            product.setMinorcategoryid(category.getId());
        }
        if (form.getPrice() != null){
            product.setPrice(form.getPrice());
        }
        if (form.getBranchId() != null){
            Condition branchCondtion = new Condition(Branch.class);
            branchCondtion.or().andEqualTo("shopId", shop.getId())
                    .andEqualTo("branchId",form.getBranchId());
            List<Branch> branchList = branchMapper.selectByCondition(branchCondtion);

            if (branchList == null || branchList.size() == 0) {
                throw new ServiceException("该店铺下不存在此分店Id");
            }
            product.setStoreid(branchList.get(0).getBranchId());
        }
        productRepository.update(product);
    }

    public JSONObject getDeviceList(ApiDeviceForm form) {

        JSONObject deskResult = new JSONObject();

        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }
        if (form.getPage() == null){
            form.setPage(1);
        }

        JSONObject params = new JSONObject();
        params.put("shopId",shop.getId());
        logger.info(params.toJSONString());

        ISqlVO iSqlVO = new ISqlVO();
        iSqlVO.setSql_id("DESK-LIST-001");
        iSqlVO.setParams(JSONObject.parseObject(params.toJSONString()));
        iSqlVO.setPage_num(form.getPage());
        iSqlVO.setPage_size(20);
        ISqlResultVO resultVO = iSqlService.runSql(iSqlVO);

        List result = resultVO.getResults();

        List<CashierDeskVO> cashierDeskList = new ArrayList<>();
        for (int i = 0;i < result.size();i++){
            JSONObject param = JSONObject.parseObject(JSON.toJSONString(result.get(i)));
            CashierDeskVO cashierDeskVO = JSON.toJavaObject(param,CashierDeskVO.class);
            cashierDeskList.add(cashierDeskVO);
            String[] splitDate=cashierDeskVO.getName().split("\\-");
            if (splitDate.length == 3){
                cashierDeskVO.setName(splitDate[2]);
            }
        }
        deskResult.put("deskList",cashierDeskList);
        deskResult = JSONObject.parseObject(deskResult.toJSONString());
        deskResult.put("totalCount",resultVO.getRecord_count());

        return deskResult;
    }

    public OrderResultVO orderList(String appId, String phone, Integer page){

        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }
        Condition condition = new Condition(BinguoOrder.class);

        if(null == phone){
            condition.or().andEqualTo("shopid", shop.getId());
        } else{
            Integer customerId = getCustomerId(phone, shop.getId());
            condition.or().andEqualTo("shopid", shop.getId())
                    .andEqualTo("customerid", customerId);
        }
        int count = binguoOrderMapper.selectCountByCondition(condition);
        int offset = getOffset(count,page);

        condition.setOrderByClause(" id desc limit " + offset + ", 20");

        List<BinguoOrder> binguoOrderList = binguoOrderMapper.selectByCondition(condition);

        OrderResultVO orderResultVO = new OrderResultVO();
        orderResultVO.setTotalCount(count);

        if (binguoOrderList != null && binguoOrderList.size() > 0) {

            List<String> orderNoList = binguoOrderList.stream().map(BinguoOrder::getOrderno).collect(Collectors.toList());

            Condition orderItemCondition = new Condition(OrderItem.class);

            orderItemCondition.or().andIn("orderno", orderNoList);

            List<OrderItem> orderItemList = orderItemMapper.selectByCondition(orderItemCondition);

            Map<String, List<OrderItem>> orderNoOrderItemMap = new HashMap<>();
            if (orderItemList != null && orderItemList.size() > 0) {
                for (OrderItem orderItem : orderItemList) {
                    List<OrderItem> tempOrderItemList = orderNoOrderItemMap.get(orderItem.getOrderno());

                    if (tempOrderItemList == null) {
                        tempOrderItemList = new ArrayList<>();
                        orderNoOrderItemMap.put(orderItem.getOrderno(), tempOrderItemList);
                    }
                    tempOrderItemList.add(orderItem);
                }
            }

            List<OrderForExternalVO> resultList = new ArrayList<>();

            for (BinguoOrder binguoOrder : binguoOrderList) {
                OrderForExternalVO orderForExternalVO = new OrderForExternalVO();
                orderForExternalVO.setCustomerId(binguoOrder.getCustomerid());
                orderForExternalVO.setCustomerName(binguoOrder.getCustomername());
                orderForExternalVO.setCustomerPhone(binguoOrder.getCustomerphone());

                List<OrderItem> orderItemL = orderNoOrderItemMap.get(binguoOrder.getOrderno());

                if (orderItemL != null) {
                    orderForExternalVO.setItemCount(orderItemL.size());
                    List<OrderItemForExternalVO> tempList = new ArrayList<>();
                    for (OrderItem o : orderItemL) {
                        OrderItemForExternalVO orderItemForExternalVO = new OrderItemForExternalVO();
                        orderItemForExternalVO.setPrice(o.getPrice());
                        orderItemForExternalVO.setProductId(o.getProductid());
                        orderItemForExternalVO.setProductName(o.getProductname());
                        orderItemForExternalVO.setQuantity(o.getQuantity());
                        orderItemForExternalVO.setRealPrice(o.getRealprice());
                        tempList.add(orderItemForExternalVO);
                    }
                    orderForExternalVO.setOrderItems(tempList);
                }else {
                    orderForExternalVO.setItemCount(0);
                }


                orderForExternalVO.setPayStatus(binguoOrder.getPaystatus());
                orderForExternalVO.setPayTime(binguoOrder.getPaytime().getTime());
                orderForExternalVO.setPayType(binguoOrder.getSource());

                if (StringUtils.isEmpty(binguoOrder.getProductOrderUrl())) {
                    if (StringUtils.hasText(binguoOrder.getSerialnumber())) {
                        orderForExternalVO.setProductOrderUrl("http://m.binguoai.com/" + binguoOrder.getSerialnumber() + ".jpg");
                    }
                }else {
                    orderForExternalVO.setProductOrderUrl(binguoOrder.getProductOrderUrl());
                }
                orderForExternalVO.setRealFee(binguoOrder.getRealfee());
                orderForExternalVO.setRefundFee(binguoOrder.getRefundfee());
                orderForExternalVO.setRefundStatus(binguoOrder.getRefundstatus());
                orderForExternalVO.setTotalFee(binguoOrder.getTotalfee());
                orderForExternalVO.setOrderNo(binguoOrder.getOrderno());
                orderForExternalVO.setOrderType(binguoOrder.getOrdertype());

                resultList.add(orderForExternalVO);
            }

            orderResultVO.setOrderList(resultList);
            return orderResultVO;
        }

        return orderResultVO;

    }

    public OrderResultVO orderLists(ApiOrderListForm orderListForm){
        Shop shop = appIdShopMap.get(orderListForm.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        if (orderListForm.getPage() == null){
            orderListForm.setPage(1);
        }
        JSONObject params = (JSONObject) JSON.toJSON(orderListForm);
        params.remove("appId");
        params.remove("sign");
        params.remove("page");
        params.put("shopId",shop.getId());
        logger.info(params.toJSONString());

        ISqlVO iSqlVO = new ISqlVO();
        iSqlVO.setSql_id("ORDER-LIST-001");
        iSqlVO.setParams(JSONObject.parseObject(params.toJSONString()));
        iSqlVO.setPage_num(orderListForm.getPage());
        iSqlVO.setPage_size(20);
        ISqlResultVO resultVO = iSqlService.runSql(iSqlVO);

        List result = resultVO.getResults();

        List<BinguoOrder> binguoOrderList = new ArrayList<>();
        for (int i = 0;i < result.size();i++){
            JSONObject param = JSONObject.parseObject(JSON.toJSONString(result.get(i)));
            BinguoOrder binguoOrder = JSON.toJavaObject(param,BinguoOrder.class);
            binguoOrderList.add(binguoOrder);
        }
        //查出所有的订单列表之后


        OrderResultVO orderResultVO = new OrderResultVO();
        orderResultVO.setTotalCount(resultVO.getRecord_count());
        if (binguoOrderList != null && binguoOrderList.size() > 0) {

            List<String> orderNoList = binguoOrderList.stream().map(BinguoOrder::getOrderno).collect(Collectors.toList());

            Condition orderItemCondition = new Condition(OrderItem.class);

            orderItemCondition.or().andIn("orderno", orderNoList);

            List<OrderItem> orderItemList = orderItemMapper.selectByCondition(orderItemCondition);

            Map<String, List<OrderItem>> orderNoOrderItemMap = new HashMap<>();
            if (orderItemList != null && orderItemList.size() > 0) {
                for (OrderItem orderItem : orderItemList) {
                    List<OrderItem> tempOrderItemList = orderNoOrderItemMap.get(orderItem.getOrderno());

                    if (tempOrderItemList == null) {
                        tempOrderItemList = new ArrayList<>();
                        orderNoOrderItemMap.put(orderItem.getOrderno(), tempOrderItemList);
                    }
                    tempOrderItemList.add(orderItem);
                }
            }

            List<OrderForExternalVO> resultList = new ArrayList<>();

            for (BinguoOrder binguoOrder : binguoOrderList) {
                OrderForExternalVO orderForExternalVO = new OrderForExternalVO();
                orderForExternalVO.setCustomerId(binguoOrder.getCustomerid());
                orderForExternalVO.setCustomerName(binguoOrder.getCustomername());
                orderForExternalVO.setCustomerPhone(binguoOrder.getCustomerphone());

                List<OrderItem> orderItemL = orderNoOrderItemMap.get(binguoOrder.getOrderno());

                if (orderItemL != null) {
                    orderForExternalVO.setItemCount(orderItemL.size());
                    List<OrderItemForExternalVO> tempList = new ArrayList<>();
                    for (OrderItem o : orderItemL) {
                        OrderItemForExternalVO orderItemForExternalVO = new OrderItemForExternalVO();
                        orderItemForExternalVO.setPrice(o.getPrice());
                        orderItemForExternalVO.setProductId(o.getProductid());
                        orderItemForExternalVO.setProductName(o.getProductname());
                        orderItemForExternalVO.setQuantity(o.getQuantity());
                        orderItemForExternalVO.setRealPrice(o.getRealprice());
                        tempList.add(orderItemForExternalVO);
                    }
                    orderForExternalVO.setOrderItems(tempList);
                }else {
                    orderForExternalVO.setItemCount(0);
                }


                orderForExternalVO.setPayStatus(binguoOrder.getPaystatus());
                orderForExternalVO.setPayTime(binguoOrder.getPaytime().getTime());
                orderForExternalVO.setPayType(binguoOrder.getSource());

                if (StringUtils.isEmpty(binguoOrder.getProductOrderUrl())) {
                    if (StringUtils.hasText(binguoOrder.getSerialnumber())) {
                        orderForExternalVO.setProductOrderUrl("http://m.binguoai.com/" + binguoOrder.getSerialnumber() + ".jpg");
                    }
                }else {
                    orderForExternalVO.setProductOrderUrl(binguoOrder.getProductOrderUrl());
                }
                orderForExternalVO.setRealFee(binguoOrder.getRealfee());
                orderForExternalVO.setRefundFee(binguoOrder.getRefundfee());
                orderForExternalVO.setRefundStatus(binguoOrder.getRefundstatus());
                orderForExternalVO.setTotalFee(binguoOrder.getTotalfee());
                orderForExternalVO.setOrderNo(binguoOrder.getOrderno());
                orderForExternalVO.setOrderType(binguoOrder.getOrdertype());

                resultList.add(orderForExternalVO);
            }

            orderResultVO.setOrderList(resultList);
            return orderResultVO;
        }
        return orderResultVO;
    }

    public void close(ApiGetCustomerInfoForm form){

        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }


        Condition condition = new Condition(Customer.class);
        condition.or().andEqualTo("phone", form.getPhone());

        List<Customer> customerList = customerRepository.findByCondition(condition);

        Customer customer = null;
        if (customerList != null && customerList.size() > 0) {
            customer = customerList.get(0);
        }

        if (customer == null) {
            throw new ServiceException("用户不存在");
        }

        Condition payCardCondition = new Condition(PayCard.class);
        payCardCondition.or().andEqualTo("shopid", shop.getId())
                .andEqualTo("customerid", customer.getId())
                .andEqualTo("cardtype", CardType.BINGUO_CARD.getCode())

        ;

        List<PayCard> payCardList = payCardMapper.selectByCondition(payCardCondition);

        if (payCardList != null && payCardList.size() > 0) {
            PayCard payCard = payCardList.get(0);

            PayCard temp = new PayCard();
            temp.setId(payCard.getId());
            temp.setDeleted(true);

            payCardMapper.updateByPrimaryKeySelective(temp);
        }
        Condition faceCondition = new Condition(Face.class);
        faceCondition.or().andEqualTo("persionid", shop.getId() + "_" + customer.getId());
        List<Face> faceList = faceRepository.findByCondition(faceCondition);
        if (faceList != null && faceList.size() > 0) {
            FaceHelperV3.deletePerson(shop.getId() + "_" + customer.getId());
            faceRepository.deleteByCondition(faceCondition);
        }


        Condition customerExtendCondition = new Condition(CustomerExtend.class);
        customerExtendCondition.or().andEqualTo("customerId", customer.getId())
                .andEqualTo("shopId", shop.getId())
        ;
        List<CustomerExtend> customerExtendList =
                customerExtendMapper.selectByCondition(customerExtendCondition);

        if (customerExtendList != null && customerExtendList.size() > 0) {
            CustomerExtend customerExtend = customerExtendList.get(0);

            if (customerExtend.getIsAudit().intValue() == 1) {
                CustomerExtend temp = new CustomerExtend();
                temp.setId(customerExtend.getId());
                temp.setIsAudit(0);

                customerExtendMapper.updateByPrimaryKeySelective(temp);
            }
        }
    }

    /**
     *
     * @param form
     * @return 用户id和faceId
     */
    public JSONObject register(ApiRegisterForm form){

        JSONObject result = new JSONObject();

        String faceResult = "人脸创建成功";

        String faceResultCode = "000";

        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        if(StringUtils.hasText(form.getCardNo())){
            PayCard payCard = customerService.findPayCard(shop.getId(),form.getCardNo());
            if (payCard != null){
                throw new ServiceException("卡号重复");
            }
        }

        CustomerGroup customerGroup = null;

        if (form.getGroupId() != null){
            Condition condition = new Condition(CustomerGroup.class);
            condition.or().andEqualTo("shopId",shop.getId())
                    .andEqualTo("id",form.getGroupId())
                    .andEqualTo("deleted",0);
            List<CustomerGroup> groupList = customerGroupRepository.findByCondition(condition);

            if (groupList == null || groupList.size() == 0){
                throw new ServiceException("该店铺下不存在该groupId");
            }
            customerGroup = groupList.get(0);

        }

        Condition condition = new Condition(Customer.class);
        condition.or().andEqualTo("phone", form.getPhone());

        List<Customer> customerList = customerRepository.findByCondition(condition);

        Customer customer;
        String faceID = null;
        if (customerList != null && customerList.size() > 0) {
            customer = customerList.get(0);
            customer.setName(form.getUsername());
            customerRepository.update(customer);

            Condition payCardCondition = new Condition(PayCard.class);
            payCardCondition.or()
                    .andEqualTo("customerid", customer.getId())
                    .andEqualTo("shopid", shop.getId())
                    .andEqualTo("cardtype", CardType.BINGUO_CARD.getCode());

            List<PayCard> payCardList = payCardMapper.selectByCondition(payCardCondition);

            if (payCardList != null && payCardList.size() > 0) {
                PayCard payCard = payCardList.get(0);
                if (payCard.getDeleted()) {
                    payCard.setDeleted(false);
                    if (StringUtils.hasText(form.getCardNo())){
                        payCard.setCardno(form.getCardNo());
                    }
                    payCardRepository.update(payCard);
                    Condition customerExtendCondition = new Condition(CustomerExtend.class);
                    customerExtendCondition.or().andEqualTo("customerId", customer.getId())
                            .andEqualTo("shopId", shop.getId());

                    List<CustomerExtend> customerExtendList = customerExtendMapper.selectByCondition(customerExtendCondition);
                    CustomerExtend customerExtend = customerExtendList.get(0);
                    if (customerExtend.getIsAudit() == 0) {
                        CustomerExtend temp = new CustomerExtend();
                        temp.setId(customerExtend.getId());
                        temp.setIsAudit(1);
                        if (customerGroup != null){
                            temp.setGroupId(temp.getGroupId());
                            temp.setGroupName(temp.getGroupName());
                        }
                        customerExtendMapper.updateByPrimaryKeySelective(temp);
                    }
                }else {
                    throw new ServiceException("用户已存在");
                }
            }else {
               shopService.createShopPayCard(shop,customer,form.getCardNo(),customerGroup);
            }
        }else {
            customer = new Customer();
            customer.setName(form.getUsername());
            customer.setCreated(new Date());
            customer.setUpdated(customer.getCreated());
            customer.setPhone(form.getPhone());
            customerRepository.save(customer);

            shopService.createShopPayCard(shop,customer,form.getCardNo(),customerGroup);
        }

        boolean faceAdded = false;
        if (!StringUtils.isEmpty(form.getFaceUrl())){

            int score = FaceHelperV3.detectFace(shop.getId(), form.getFaceUrl());
            if (score < 70) {
                faceResult = "人脸图片质量不合格";
                faceResultCode = "001";
            }
            Condition tempFaceExample = new Condition(Face.class);
            tempFaceExample.or().andEqualTo("customerId",customer.getId())
                    .andEqualTo("persionid", shop.getId() + "_" + customer.getId());


            List<Face> faceList = faceRepository.findByCondition(tempFaceExample);
            if (faceList != null && faceList.size() > 0){
               for (Face face : faceList){
                   if (face.getFaceurl().equals(form.getFaceUrl())) {
                       faceAdded = true;
                       break;
                   }
               }
               if (!faceAdded){
                   faceID = FaceHelperV3.addFace(shop.getId() + "_" + customer.getId(), form.getFaceUrl());
               }
            } else {
                faceID = FaceHelperV3.createPerson(String.valueOf(shop.getId()),
                        shop.getId() + "_" + customer.getId(), form.getFaceUrl());
            }

        }
        //此图片未创建
        if (faceID != null) {
            Face temp = new Face();
            temp.setFaceid(faceID);
            temp.setCustomerId(customer.getId());
            temp.setFaceurl(form.getFaceUrl());
            temp.setPersionid(shop.getId() + "_" + customer.getId());
            faceRepository.save(temp);
        }else {
            faceResult = "人脸创建失败";
            faceResultCode = "002";
        }

        result.put("faceId",faceID);
        result.put("faceResultCode",faceResultCode);
        result.put("faceResult",faceResult);
        result.put("customerId",customer.getId());
        return result;
    }


    public void recharge(ApiRechargeForm rechargeForm) {

        Shop shop = appIdShopMap.get(rechargeForm.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        Condition orderCondition = new Condition(BinguoOrder.class);
        orderCondition.or().andEqualTo("transactionid",rechargeForm.getOrderNo())
                .andEqualTo("shopid",shop.getId());
        List<BinguoOrder> orderList = binguoOrderRepository.findByCondition(orderCondition);
        if (orderList != null && orderList.size() >0){
            throw new ServiceException("充值订单重复");
        }

        String phone = rechargeForm.getPhone();

        String amount = rechargeForm.getAmount();

        LogAbcBankRecharge logAbcBankRecharge = new LogAbcBankRecharge();
        logAbcBankRecharge.setAmount(rechargeForm.getAmount());
        logAbcBankRecharge.setCreateTime(new Date());
        logAbcBankRecharge.setOrderNo(rechargeForm.getOrderNo());
        logAbcBankRecharge.setUsername(rechargeForm.getUsername());
        logAbcBankRecharge.setPhone(rechargeForm.getPhone());
        logAbcBankRecharge.setRechargeTime(rechargeForm.getOrderTime());
        logAbcBankRechargeRepository.save(logAbcBankRecharge);

        if (StringUtils.hasText(amount) && Long.valueOf(amount) >= 0) {

            LoggerUtil.console.info("recharge, phone:{}, amount:{}", phone, amount);
        } else {
            throw new ServiceException("金额不正确");
        }


        Condition customerCondition = new Condition(Customer.class);
        customerCondition.or().andEqualTo("phone", phone);
        List<Customer> customerList = customerRepository.findByCondition(customerCondition);

        Integer customerId = null;
        Customer customer = null;
        if (customerList != null && customerList.size() > 0) {
            customer = customerList.get(0);

            customerId = customer.getId();
        }

        if (customerId == null) {
            throw new ServiceException("用户不存在");
        }

        Condition condition = new Condition(PayCard.class);

        condition.or().andEqualTo("customerid", customerId).andEqualTo("shopid", shop.getId())
                .andEqualTo("cardtype", CardType.BINGUO_CARD.getCode())
        ;

        List<PayCard> payCardList = payCardMapper.selectByCondition(condition);

        PayCard payCard = null;
        if (payCardList != null && payCardList.size() > 0) {
            payCard = payCardList.get(0);

            PayCard temp = new PayCard();
            temp.setId(payCard.getId());
            temp.setDeleted(false);
            temp.setAccountbalance(payCard.getAccountbalance() + Long.valueOf(amount));

            payCardMapper.updateByPrimaryKeySelective(temp);

        }else {
            throw new ServiceException("用户不存在");
        }



        String orderNo = UUID.randomUUID().toString().replace("-", "");
        BinguoOrder order = BinguoOrder.builder()
                .orderno(orderNo)
                .transactionid(rechargeForm.getOrderNo())
                .cardid(payCard.getId())
                .shopid(shop.getId())
                .openid(customer.getOpenid())
                .customerid(customerId)
                .customername(customer.getName())
                .customerphone(customer.getPhone())
                .source(PayType.OTHERPAY.getCode().byteValue())
                .totalfee(Long.valueOf(amount))
                .realfee(Long.valueOf(amount))
                .totalquantity(1)
                .ordertype(OrderType.CARD.getCode())
                .paystatus(PayStatus.SUCCESS.getCode().byteValue())
                .refundstatus(RefundStatus.UN_REFUND.getCode().byteValue())
                .build();
        binguoOrderMapper.insertSelective(order);
    }

    public ApiUserListVO getUserList(ApiGetCustomerInfoListForm getCustomerInfoForm){
        Shop shop = appIdShopMap.get(getCustomerInfoForm.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        Condition payCardCondition = new Condition(PayCard.class);
        payCardCondition.or().andEqualTo("shopid", shop.getId())
                .andEqualTo("cardtype", CardType.BINGUO_CARD.getCode())
                .andEqualTo("deleted", 0)
        ;
        if(null != getCustomerInfoForm.getCardNo()){
            payCardCondition.or().andEqualTo("cardno",getCustomerInfoForm.getCardNo());
        }

        int count = payCardMapper.selectCountByCondition(payCardCondition);

        if (getCustomerInfoForm.getPage() < 1) {
            getCustomerInfoForm.setPage(1);
        }

        int offset = (getCustomerInfoForm.getPage() - 1) * 20;

        payCardCondition.setOrderByClause(" id desc limit " + offset + ", 20");

        List<PayCard> payCardList = payCardMapper.selectByCondition(payCardCondition);

        ApiUserListVO apiUserListVO = new ApiUserListVO();
        apiUserListVO.setTotalCount(count);

        if (payCardList != null && payCardList.size() > 0) {
            List<Integer> customerIdList = payCardList.stream().map(PayCard::getCustomerid).collect(Collectors.toList());
            Map<Integer, PayCard> customerIdPayCardMap = payCardList.stream()
                    .collect(Collectors.toMap(PayCard::getCustomerid, p->p));

            Condition customerCondition = new Condition(Customer.class);
            customerCondition.or().andIn("id", customerIdList);
            List<Customer> customerList = customerRepository.findByCondition(customerCondition);


            apiUserListVO.setCustomerList(new ArrayList<>());
            for (Customer customer : customerList) {
                PayCard payCard = customerIdPayCardMap.get(customer.getId());
                ApiCustomerVO apiCustomerVO = new ApiCustomerVO();
                apiCustomerVO.setBalance(payCard.getAccountbalance() + payCard.getWxAccountbalance()
                        + payCard.getYktAccountbalance() + payCard.getBzAccountbalance());

                apiCustomerVO.setCardNo(payCard.getCardno());
                apiCustomerVO.setCustomerId(customer.getId());
                apiCustomerVO.setCustomerName(customer.getName());
                apiCustomerVO.setPhone(customer.getPhone());

                apiUserListVO.getCustomerList().add(apiCustomerVO);
            }

        }
        return apiUserListVO;
    }


    public ApiProductListVO getProductList(String appId, Integer page,Integer branchId){
        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        Condition productCondition = new Condition(Product.class);
        Example.Criteria criteria = productCondition.or();
        criteria.andEqualTo("shopid", shop.getId())
                .andEqualTo("deleted", false);
        if (branchId != null) {
           criteria.andEqualTo("storeid",branchId);
        }

        int count = productMapper.selectCountByCondition(productCondition);

        if (page == null || page < 1) {
            page = 1;
        }

        int offset = (page - 1) * 20;

        productCondition.setOrderByClause(" id desc limit " + offset + ", 20");

        List<Product> productList = productMapper.selectByCondition(productCondition);

        ApiProductListVO apiProductListVO = new ApiProductListVO();
        apiProductListVO.setTotalCount(count);

        if (productList != null && productList.size() > 0) {
            apiProductListVO.setProductList(new ArrayList<>());

            for (Product product : productList) {
                ApiProductVO apiProductVO = new ApiProductVO();
                apiProductVO.setProductId(product.getSearchcode());
                apiProductVO.setProductName(product.getName());
                apiProductVO.setProductImage(product.getProductpic());
                apiProductVO.setProductPrice(product.getPrice());

                apiProductListVO.getProductList().add(apiProductVO);
            }
        }
        LoggerUtil.console.info("菜品查询成功:"+apiProductListVO);
        return apiProductListVO;
    }


    public PayCard getPayCard(Integer customerId, String appId){
        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        Condition payCardCondition = new Condition(PayCard.class);
        payCardCondition.or().andEqualTo("shopid", shop.getId())
                .andEqualTo("customerid", customerId)
                .andEqualTo("cardtype", CardType.BINGUO_CARD.getCode())
                .andEqualTo("deleted", 0)

        ;

        List<PayCard> payCardList = payCardMapper.selectByCondition(payCardCondition);

        if (payCardList != null && payCardList.size() > 0) {
            PayCard payCard = payCardList.get(0);

            String payCode = BarcodeUtil.createPayCode("" + payCard.getId());

            PayCard temp = new PayCard();

            temp.setPayCode(payCode);
            temp.setId(payCard.getId());
            temp.setPayCodeTime(new Date());

            payCardMapper.updateByPrimaryKeySelective(temp);

            payCard.setPayCode(payCode);

            return payCard;
        }
        return null;
    }


    private String createPayCardAndFace(Integer shopId, Integer customerId, String faceUrl, String shopName, String cardNo){

        PayCard payCard = PayCard.builder()
                .shopid(Integer.valueOf(shopId))
                .customerid(customerId)
                .cardno(cardNo)
                .cardtype(CardType.BINGUO_CARD.getCode().byteValue())
                .deleted(false)
                .name(shopName + "卡")
                .bzAccountbalance(0l)
                .wxAccountbalance(0l)
                .yktAccountbalance(0l)
                .accountbalance(0l)
                .ismaster(true)
                .isnopasswordpay(true)
                .build();

        payCardMapper.insertSelective(payCard);

        if (StringUtils.isEmpty(cardNo)) {
            PayCard tempPaycard = new PayCard();
            tempPaycard.setCardno(payCard.getId() + "");
            tempPaycard.setId(payCard.getId());

            payCardMapper.updateByPrimaryKeySelective(tempPaycard);
        }

        addCustomerExtend(shopId, customerId);

        String faceID = FaceHelperV3.createPerson(String.valueOf(shopId),
                shopId + "_" + customerId, faceUrl);

        return faceID;
    }

    private void addCustomerExtend(Integer shopId, Integer customerId) {
        Condition customerExtendCondition = new Condition(CustomerExtend.class);
        customerExtendCondition.or().andEqualTo("customerId", customerId)
            .andEqualTo("shopId", shopId)
        ;
        List<CustomerExtend> customerExtendList =
                customerExtendMapper.selectByCondition(customerExtendCondition);

        if (customerExtendList != null && customerExtendList.size() > 0) {
            CustomerExtend customerExtend = customerExtendList.get(0);

            if (customerExtend.getIsAudit().intValue() == 0) {
                CustomerExtend temp = new CustomerExtend();
                temp.setId(customerExtend.getId());
                temp.setIsAudit(1);

                customerExtendMapper.updateByPrimaryKeySelective(temp);
            }
        }else {
            CustomerExtend customerExtend = new CustomerExtend();
            customerExtend.setShopId(shopId);
            customerExtend.setCustomerId(customerId);
            customerExtend.setIsAudit(1);
            customerExtend.setUserStatus(1);
            customerExtendMapper.insertSelective(customerExtend);
        }
    }


    private Integer getCustomerId(String phone, Integer shopId) {
        Condition condition = new Condition(Customer.class);
        condition.or().andEqualTo("phone", phone);

        List<Customer> customerList = customerRepository.findByCondition(condition);

        Customer customer = null;
        if (customerList != null && customerList.size() > 0) {
            customer = customerList.get(0);
        }

        if (customer == null) {
            throw new ServiceException("用户不存在");
        }
        Condition payCardCondition = new Condition(PayCard.class);
        payCardCondition.or().andEqualTo("shopid", shopId)
                .andEqualTo("customerid", customer.getId())
                .andEqualTo("cardtype", CardType.BINGUO_CARD.getCode());
        List<PayCard> payCardList = payCardMapper.selectByCondition(payCardCondition);
        if (payCardList != null && payCardList.size() > 0) {
            return customer.getId();
        }
        throw new ServiceException("用户不存在");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        List<Shop> shopList = shopRepository.findAll();

        appIdShopMap = new HashMap<>();
        for (Shop shop : shopList) {
            if (StringUtils.hasText(shop.getAppId())) {
                appIdShopMap.put(shop.getAppId(), shop);
            }
        }
    }


    @Scheduled(cron="0 0/10 * * * ?") //每十分钟更新商户信息
    public void updateShopInfo() throws Exception {
        afterPropertiesSet();
    }

    @Resource
    private BaiduRecUtil baiduRecUtil;
    @Resource
    private LogProductImgMapper logProductImgMapper;

    @Resource
    private LogProductImgCurMapper logProductImgCurMapper;
    @Resource
    private LogProductImgFromUserMapper logProductImgFromUserMapper;

    @Resource
    private LogShopBaiduImgDelMapper logShopBaiduImgDelMapper;


    private void addImg(Integer productId, String imgUrl, Integer branchId, Integer shopId){
        //添加新图片
//        ThreadManager.executorService.execute(() -> {
        try {

            String filepath = "/usr/local/nginx/html/images/source/" + shopId + "/" + productId;
            File file = new File(filepath);

            if (!file.exists()) {
                file.mkdir();
            }

            String filename = filepath + "/" + UUID.randomUUID() + ".png";

            FileDownloader.downloadNet(imgUrl, filename);

            String cont_sign = baiduRecUtil.addImg(shopId, branchId, filename, shopId + "_" + productId);

            LogProductImg logProductImg = new LogProductImg();
            logProductImg.setCutImg(imgUrl);
            logProductImg.setProductId(productId);
            logProductImg.setShopId(shopId);
            logProductImg.setSourceImg(imgUrl);
            logProductImg.setCreateTime(new Date());
            logProductImg.setContSign(cont_sign);
            logProductImg.setBaiduDeleted(0);
            logProductImg.setFromWxUpload(1);
            logProductImg.setBranchId(branchId);

            logProductImgMapper.insert(logProductImg);


            Product product = new Product();
            product.setProductpic(imgUrl);
            product.setId(productId);
            productMapper.updateByPrimaryKeySelective(product);

        } catch (Exception e) {
            e.printStackTrace();
        }
//        });
    }

    public void delImg(Integer productId, Integer branchId, Integer shopId){

        //删除微信上传图片
        Condition logProductImgCondtion = new Condition(LogProductImg.class);
        logProductImgCondtion.or().andEqualTo("shopId", shopId)
                .andEqualTo("baiduDeleted", 0)
                .andEqualTo("productId", productId)
        ;

        List<LogProductImg> logProductImgList = logProductImgMapper.selectByCondition(logProductImgCondtion);
        if (logProductImgList != null && logProductImgList.size() > 0) {
            ThreadManager.executorService.execute(() -> {
                for (LogProductImg logProductImg : logProductImgList) {
                    String contSign = logProductImg.getContSign();
                    if(!baiduRecUtil.delImg(contSign, shopId, branchId)){
                        LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                        logShopBaiduImgDel.setImgType(1);
                        logShopBaiduImgDel.setLogId(logProductImg.getId());
                        logShopBaiduImgDel.setStatus(0);
                        logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                    }else{
                        LogProductImg temp = new LogProductImg();
                        temp.setId(logProductImg.getId());
                        temp.setBaiduDeleted(1);
                        logProductImgMapper.updateByPrimaryKeySelective(temp);
                    }
                }
            });
        }


        //删除纠正图片
        Condition logProductImgFromUserCondtion = new Condition(LogProductImgFromUser.class);
        logProductImgFromUserCondtion.or().andEqualTo("shopId", shopId)
                .andEqualTo("productId", productId)
                .andEqualTo("baiduDeleted", 0)
        ;

        List<LogProductImgFromUser> logProductImgFromUserList = logProductImgFromUserMapper.selectByCondition(logProductImgFromUserCondtion);
        if (logProductImgFromUserList != null && logProductImgFromUserList.size() > 0) {
            ThreadManager.executorService.execute(() -> {
                for (LogProductImgFromUser logProductImgFromUser : logProductImgFromUserList) {
                    String contSign = logProductImgFromUser.getContSign();
                    if(!baiduRecUtil.delImg(contSign, shopId, branchId)){
                        LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                        logShopBaiduImgDel.setStatus(0);
                        logShopBaiduImgDel.setLogId(logProductImgFromUser.getId());
                        logShopBaiduImgDel.setImgType(2);
                        logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                    }else{
                        LogProductImgFromUser temp = new LogProductImgFromUser();
                        temp.setId(logProductImgFromUser.getId());
                        temp.setBaiduDeleted(1);
                        logProductImgFromUserMapper.updateByPrimaryKeySelective(temp);
                    }
                }
            });
        }

        //删除小库纠正图片
        Condition logProductImgCurCondtion = new Condition(LogProductImgCur.class);
        logProductImgCurCondtion.or().andEqualTo("shopId", shopId)
                .andEqualTo("productId", productId)
                .andEqualTo("baiduDeleted", 0)
        ;

        List<LogProductImgCur> logProductImgCurList = logProductImgCurMapper.selectByCondition(logProductImgCurCondtion);
        if (logProductImgCurList != null && logProductImgCurList.size() > 0) {
            ThreadManager.executorService.execute(() -> {
                for (LogProductImgCur logProductImgCur : logProductImgCurList) {
                    String contSign = logProductImgCur.getContSign();
                    if(baiduRecUtil.delImgCur(contSign, shopId, branchId)){
                        LogProductImgCur temp = new LogProductImgCur();
                        temp.setBaiduDeleted(1);
                        temp.setId(logProductImgCur.getId());
                        logProductImgCurMapper.updateByPrimaryKeySelective(temp);
                    }
                }
            });
        }
    }
    public ApiUserListVO getUserLists(ApiGetCustomerInfoListForm getCustomerInfoForm){
        Shop shop = appIdShopMap.get(getCustomerInfoForm.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }
        int count = customerMapper.selectCustomerCount(shop.getId(),getCustomerInfoForm);
        //查询出的数据数量小于一页
        if(count/20 < 1){
            getCustomerInfoForm.setPage(0);
        }else{
            int offset = getOffset(getCustomerInfoForm.getPage(),count);
            getCustomerInfoForm.setPage(offset);
        }
        ApiUserListVO apiUserListVO = new ApiUserListVO();
        getCustomerInfoForm.setPage(getCustomerInfoForm.getPage());
        List<ApiCustomerVO> customers=customerMapper.selectCustomer(shop.getId(),getCustomerInfoForm);
        apiUserListVO.setCustomerList(customers);
        apiUserListVO.setTotalCount(count);
        return apiUserListVO;
    }

   /* public OrderResultVO orderLists(String appId,  Integer page){

        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }
        int count = binguoOrderMapper.findOrderCount(shop.getId());
        int offset = getOffset(count,page);
        List<OrderForExternalVO> orderForExternalVOS = binguoOrderMapper.findOrder(shop.getId(),offset);
        for(OrderForExternalVO orderForExternalVO : orderForExternalVOS){
           Condition condition = new Condition(OrderItem.class);
           condition.or().andEqualTo("orderno");


        }

        return null;

    }*/

    public int getOffset(int page,int count){
        if(page == 0){
            page=1;
        }
        //总数据条数正好被20整除
        if(count % 20 == 0){
            //输入页数数据大于总数据数量
            if((page-1)*20 > count){
                return count-20;
                //数据页数数据小于总数据数量
            }else if((page-1)*20 < count){
                return (page-1)*20;
                //输入页数数据正好等于总数据数量
            }else{
                return (page-1)*20-20;
            }
        }else{
            //不被整除
            if((page-1)*20 > count){
                return count-count%20;
            }else{
                return (page-1)*20 ;
            }
        }
    }
    public Branch addBranch(ApiBranchEditForm branchEditForm){
        Shop shop = appIdShopMap.get(branchEditForm.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }
        if (null == branchService.checkBranchName(branchEditForm.getBranchName())) {
            Branch branch = new Branch();
            branch.setBranchId(0);
            branch.setShopId(shop.getId());
            branch.setBranchName(branchEditForm.getBranchName());
            branch.setBranchPricetype(0);
            branchMapper.insertSelective(branch);
            return branch;
        }else {
            throw new ServiceException("分店名称重复");
        }
    }

    public Integer updateBranch(ApiBranchEditForm branchEditForm){
        Shop shop = appIdShopMap.get(branchEditForm.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }
        if (null == branchService.checkBranchName(branchEditForm.getBranchName())) {
            Branch branch = new Branch();
            branch.setBranchId(branchEditForm.getBranchId());
            branch.setShopId(shop.getId());
            branch.setBranchName(branchEditForm.getBranchName());
            branch.setBranchPricetype(0);
            return branchMapper.updateByPrimaryKeySelective(branch);
        }else {
            throw new ServiceException("分店名称重复");
        }
    }

    public Boolean deleteFace(ApiFaceDeleteForm apiFaceDeleteForm){
        Shop shop = appIdShopMap.get(apiFaceDeleteForm.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        String persionId = apiFaceDeleteForm.getCustomerId();

        if(!persionId.matches("^[0-9]*[1-9][0-9]*$")) {
            persionId = shop.getId() + "_" + persionId;
        }

        if (apiFaceDeleteForm.getFaceId() != null) {
            return FaceHelperV3.deleteFace(persionId, apiFaceDeleteForm.getFaceId());
        }else {
            return FaceHelperV3.deletePerson(persionId);
        }
    }

    public int updateUser(ApiGetCustomerInfoListForm form) {
        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        int flag = 0;
        flag = customerMapper.updateByPrimaryKeySelective(
                Customer.builder().id(Integer.valueOf(form.getUserId()))
                        .name(form.getUserName()).phone(form.getPhone()).build());
        return flag;
    }

    public boolean openSideBoardCell(ApiOpencellForm form){
        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        SideBoard sideBoard = sideBoardMapper.selectByPrimaryKey(form.getSideBoardId());
        Map<String, String> parm = new HashMap<String, String>();
        String str = JSON.toJSONString(form.getInfo());
        parm.put("msg",str);
        parm.put("id",sideBoard.getJpushRegisterId());
        boolean flag =  JPushUtil.jpushAndroid(parm);
        RequestApiRecord record = new RequestApiRecord();
        if(flag){
            record.setId(0);
            record.setCode(200);
            record.setMessage(str);
            record.setShopId(shop.getId());
            record.setTime(new Date());
            requestApiRecordMapper.insertSelective(record);
            return flag;
        }else{
            record.setId(0);
            record.setCode(400);
            record.setMessage(str);
            record.setShopId(shop.getId());
            record.setTime(new Date());
            requestApiRecordMapper.insertSelective(record);
            return flag;
        }

    }

    public List<ShopSideBoardVO> getSideBoardList(ApiGetSideBoardListForm form){
        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        return sideBoardMapper.selectByShopId(shop.getId());
    }

    public Shop isTrueShop(String appId){
        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
            return shop;
        } else {
            return null;
        }
    }

    public Customer isShopCustomer(String phone,Shop shop){
        return customerMapper.selectCustomerByPhoneAndShopId(phone,shop.getId());
    }

    public String getKeyByAppID(String appId){
        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
            return shop.getSecurityKey();
        } else {
            shop = shopService.getShopByAppId(appId);
            if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
                LoggerUtil.console.info("shop info:{}", shop.getName());
                return shop.getSecurityKey();
            }
            throw new ServiceException("商户状态异常");
        }
    }

    public String getKeyByChannelNo(String channelNo){

        Condition condition = new Condition(ShopChannel.class);
        condition.or().andEqualTo("channelNo",channelNo);
        List<ShopChannel> shopChannelList = shopChannelRepository.findByCondition(condition);

        if (null != shopChannelList && shopChannelList.size() > 0){
            return shopChannelList.get(0).getChannelSecret();
        } else {
            throw new ServiceException("渠道号错误");
        }
    }

    public Boolean addEmployee(ApiEmployeeForm form){
        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }
        Integer count = employeeMapper.isDoubleEmplyoee(form.getAccount(),shop.getId());
        if(count > 0){
            throw new ServiceException("账号已被注册");
        }else{
            Employee employee = Employee.builder().account(form.getAccount()).created(new Date()).deleted(Boolean.FALSE).shopid(shop.getId()).
                    name(form.getAccount()).password(form.getPassword()).updated(new Date()).status(Byte.decode("0")).build();
            int i = employeeMapper.insertSelective(employee);
            LoggerUtil.console.info("新增员工结果:"+i);
            if(i>0){
                return true;
            }
            return false;
        }
    }

    public Boolean updateEmployee(ApiEmployeeForm form){
        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }
        Employee employee = employeeMapper.selectEmplyoeeByAccount(form.getAccount(),shop.getId());
        if(null == employee ){
            throw new ServiceException("未查询到该用户");
        }else{
            employee.setPassword(form.getPassword());
            int i = employeeMapper.updateByPrimaryKeySelective(employee);
            LoggerUtil.console.info("修改密码结果:"+i);
            if(i>0){
                return true;
            }
            return false;
        }
    }

    public Boolean settlementCreat(ManKeBaoOrderForm orderForm,String appid)throws Exception{
        Shop shop = appIdShopMap.get(appid);
        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }
        NormalConfig normalConfig = normalConfigMapper.selectByShopIdAndType(shop.getId());
        String method = "api.pay.order.settlement.create";
        String key = getManKeBaoKey(shop.getPhone(),appid,normalConfig.getValue()+"/report/api/v1/open/supplier/gerSupplierSecretKey");
//        String key = "fcb65648cb8d454d9a15b888538b248d";

        //签名流程
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("method", method);
        treeMap.put("supplierCode", "400140");
        treeMap.put("requestId", String.valueOf(System.currentTimeMillis()));
        treeMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
        treeMap.put("version", "1.0");
        treeMap.put("data", JSON.toJSONString(orderForm));
        String content = JSON.toJSONString(treeMap);
        String sign = manKeBaosign(content,key);
        logger.info("满客宝签名:"+sign);
        if(sign.equals("")){
            throw new ServiceException("满客宝key获取失败");
        }
        treeMap.put("sign",sign);
        normalConfig = normalConfigMapper.selectByShopIdAndType(shop.getId());
        Map result = UrlUtils.send3(normalConfig.getValue()+"/open/api",treeMap,"utf-8");
        if(String.valueOf(result.get("code")).equals("10000")){
            return true;
        }
        logger.info("满客宝错误信息:"+String.valueOf(result.get("message")));
        return false;
    }

    public String getManKeBaoKey(String phone,String appid,String url) throws Exception{
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("supplierCode", "400140");
        treeMap.put("keyType", "2");
        treeMap.put("source", "YUN_PENG");
        String key = getKeyByAppID(appid);
        String sign = ApiController.generateSign(treeMap,key);
        treeMap.put("sign",sign);

        Map map = UrlUtils.send3(url,treeMap,"utf-8");
        if(map.get("code").equals(200) && !StringUtils.isEmpty(map.get("md5Key"))){
            return map.get("md5Key").toString();
        }else{
            return null;
        }
    }

    //签名
    public String manKeBaosign(String data, String key) throws Exception {
        logger.info(" 参与生成满客宝MD5签名参数:"+data);
        logger.info(" 参与生成满客宝MD5签名key:"+key);
        //得到明文的字节数组
        byte[] btInput = (data + key).getBytes();
        // 创建一个提供信息摘要算法的对象(MD5摘要算法)
        MessageDigest messageDigest = MessageDigest.getInstance(MD5);
        // 使用指定的字节更新摘要
        messageDigest.update(btInput);
        return String.format("%032x", new BigInteger(1, messageDigest.digest()));
    }

    public JSONObject getCustomerGroupList(ApiCustomerGroupListForm customerGroupListForm) {

        JSONObject groupResult = new JSONObject();

        Shop shop = appIdShopMap.get(customerGroupListForm.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        if (customerGroupListForm.getPage() == null) {
            customerGroupListForm.setPage(1);
        }
        JSONObject params = (JSONObject) JSON.toJSON(customerGroupListForm);
        params.remove("appId");
        params.remove("sign");
        params.remove("page");
        params.put("shopId", shop.getId());
        logger.info(params.toJSONString());

        ISqlVO iSqlVO = new ISqlVO();
        iSqlVO.setSql_id("GROUP-LIST-001");
        iSqlVO.setParams(JSONObject.parseObject(params.toJSONString()));
        iSqlVO.setPage_num(customerGroupListForm.getPage());
        iSqlVO.setPage_size(20);
        ISqlResultVO resultVO = iSqlService.runSql(iSqlVO);

        List result = resultVO.getResults();

        List<CustomerGroup> customerGroupList = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            JSONObject param = JSONObject.parseObject(JSON.toJSONString(result.get(i)));
            CustomerGroup group  = JSON.toJavaObject(param, CustomerGroup.class);
            group.setDeleted(null);
            group.setShopId(null);
            customerGroupList.add(group);
        }
        groupResult.put("groupList",customerGroupList);
        groupResult = JSONObject.parseObject(groupResult.toJSONString());
        groupResult.put("totalCount",resultVO.getRecord_count());
        groupResult.put("pageSize",resultVO.getPage_size());
        groupResult.put("pageNum",resultVO.getPage_num());

        return groupResult;
    }

    public JSONObject saveCustomerGroup(ApiCustomerGroupCreateForm form){

        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        CustomerGroup customerGroup = customerService.saveCustomerGroup(form.getName(),shop.getId());
        JSONObject result = new JSONObject();

        result.put("id",customerGroup.getId());
        result.put("groupName",customerGroup.getGroupName());

        return result;
    }


    public void updateCustomerGroup(String name,
                                    Integer id,
                                    String appId){

        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        customerService.updateCustomerGroup(name,id,shop.getId());
    }

    public JSONObject getProductCategoryList(String appId,
                                             Integer pageNum) {

        JSONObject groupResult = new JSONObject();

        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        if (pageNum == null) {
            pageNum = 1;
        }
        JSONObject params = new JSONObject();

        params.put("shopId", shop.getId());
        logger.info(params.toJSONString());

        ISqlVO iSqlVO = new ISqlVO();
        iSqlVO.setSql_id("PRODUCTCATEGORY-LIST-001");
        iSqlVO.setParams(JSONObject.parseObject(params.toJSONString()));
        iSqlVO.setPage_num(pageNum);
        iSqlVO.setPage_size(20);
        ISqlResultVO resultVO = iSqlService.runSql(iSqlVO);

        List result = resultVO.getResults();

        List<ProductCategory> productCategoryList = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            JSONObject param = JSONObject.parseObject(JSON.toJSONString(result.get(i)));
            ProductCategory productCategory  = JSON.toJavaObject(param, ProductCategory.class);
            productCategory.setShopid(null);
            productCategory.setDeleted(null);
            productCategory.setType(null);
            productCategory.setParentid(null);
            productCategoryList.add(productCategory);
        }
        groupResult.put("groupList",productCategoryList);
        groupResult = JSONObject.parseObject(groupResult.toJSONString());
        groupResult.put("totalCount",resultVO.getRecord_count());
        groupResult.put("pageSize",resultVO.getPage_size());
        groupResult.put("pageNum",resultVO.getPage_num());

        return groupResult;
    }

    public JSONObject saveProductCategory(String appId,
                                          String name){

        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        ProductCategory productCategory = productService.saveProductCategory(shop.getId(),name);
        JSONObject result = new JSONObject();

        result.put("id",productCategory.getId());
        result.put("name",productCategory.getName());

        return result;
    }

    public Boolean addProductImg(String appId,
                                 Integer productId,
                                 String productUrl,
                                 String productBase64){

        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        Condition condition = new Condition(MdmsCType.class);
        condition.or().andEqualTo("tableName","shop")
                .andEqualTo("fieldName","product_rec_type")
                .andEqualTo("typeNumId",shop.getProductRecType())
                .andEqualTo("dataStatus",1);

        List<MdmsCType> typeList = mdmsCTypeRepository.findByCondition(condition);

        if (null == typeList || typeList.size() == 0){
            throw new ServiceException("该店铺菜品识别方式不适用于此接口");
        }

        if (StringUtils.isEmpty(productUrl)){
            productUrl = uploadFileService.uploadImg(shop.getId(),2,productBase64,"png");
            if (StringUtils.isEmpty(productUrl)){
                throw new ServiceException("菜品图片Base64转译出错");
            }
        }

        Product product = productService.getProductById(productId);

        boolean result = bowlService.checkBowlLocation(product.getShopid(), product.getId(), product.getStoreid(), productUrl);

        return result;
    }

    public List<ProductImgVO> getProductImgList(String appId,
                                                Integer productId){


        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        Product product = productRepository.findById(productId);

        if (product == null){
            throw new ServiceException("传入的ProductId不存在");
        }

        if (!product.getShopid().equals(shop.getId())){
            throw new ServiceException("传入的ProductId 不属于该分店");
        }

        List<LogProductImg> logProductImgList = productService.getProductImgByProductId(productId);
        List<ProductImgVO> productImgVOList = new ArrayList<>();
        if (logProductImgList != null && logProductImgList.size() > 0) {
            for (LogProductImg logProductImg : logProductImgList) {
                ProductImgVO productImgVO = new ProductImgVO();
                if (logProductImg.getSourceImg() != null && logProductImg.getSourceImg().startsWith("http")) {
                    productImgVO.setImgUrl(logProductImg.getSourceImg());
                }else{
                    if (logProductImg.getImgCutNetUrl() != null &&  logProductImg.getImgCutNetUrl().startsWith("http")) {
                        productImgVO.setImgUrl(logProductImg.getImgCutNetUrl());
                    }else {
                        continue;
                    }
                }
                productImgVO.setProductImgId(logProductImg.getId());

                productImgVOList.add(productImgVO);
            }
        }
        return productImgVOList;
    }

    public void deleteProductImg(String appId,
                                 Integer productId,
                                 Integer productImgId){

        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        Product product = productService.getProductById(productId);

        if (product == null) {
            throw new ServiceException("产品不存在");
        }
        List<LogProductImg> logProductImgList = productService.getProductImgByProductId(productId);
        if (logProductImgList.size() == 0) {
            throw new ServiceException("菜品图片数量必须大于一张");
        }

        LogProductImg temp = productService.getProductImgById(productId);

        if (StringUtils.hasText(temp.getContSign())) {
            if(!baiduRecUtil.delImg(temp.getContSign(), temp.getShopId(), temp.getBranchId())){
                LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                logShopBaiduImgDel.setLogId(temp.getId());
                logShopBaiduImgDel.setStatus(0);

                logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
            }
        }

        String imgCutUrl = productService.delProductImg(productImgId);

        if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 4) {
            ypRecService.delImg(imgCutUrl, product.getStoreid(), bowlService.localRecIp);
        }

        if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 6) {
            shopProductMsgService.addDeleteProductImgMessage(temp);
        }

    }

    public void customerPay(String appId,
                            Integer customerId,
                            String cardNo,
                            String cardId,
                            Long realFee){

        Shop shop = appIdShopMap.get(appId);

        PayCard payCard = new PayCard();

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        if (customerId == null && StringUtils.isEmpty(cardId) && StringUtils.isEmpty(cardNo)){
            throw new ServiceException("参数错误");
        }

        if (customerId != null){
            payCard = customerService.getCustomerPayCard(customerId,shop.getId());
        }

        if (!StringUtils.isEmpty(cardId)){
            cardNo = ypCardService.getCardNo(cardId,shop.getId());
            payCard = customerService.findPayCard(shop.getId(),cardNo);
        }

        if (!StringUtils.isEmpty(cardNo)){
           payCard = customerService.findPayCard(shop.getId(),cardNo);
        }

        String orderNo = orderNoBuilder.createPlatformOrderNo();

        customerService.customerPay(payCard,realFee,orderNo);
    }

    public JSONObject getBranchList(String appId,
                                    Integer pageNum) {

        JSONObject branchResult = new JSONObject();

        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        if (pageNum == null) {
            pageNum = 1;
        }
        JSONObject params = new JSONObject();

        params.put("shopId", shop.getId());
        logger.info(params.toJSONString());

        ISqlVO iSqlVO = new ISqlVO();
        iSqlVO.setSql_id("BRANCH-LIST-001");
        iSqlVO.setParams(JSONObject.parseObject(params.toJSONString()));
        iSqlVO.setPage_num(pageNum);
        iSqlVO.setPage_size(20);
        ISqlResultVO resultVO = iSqlService.runSql(iSqlVO);

        List result = resultVO.getResults();

        List<Branch> branchList = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            JSONObject param = JSONObject.parseObject(JSON.toJSONString(result.get(i)));
            Branch branch  = JSON.toJavaObject(param, Branch.class);
            branch.setShopId(null);
            branch.setBranchPricetype(null);
            branchList.add(branch);
        }
        branchResult.put("branchList",branchList);
        branchResult = JSONObject.parseObject(branchResult.toJSONString());
        branchResult.put("totalCount",resultVO.getRecord_count());
        branchResult.put("pageSize",resultVO.getPage_size());
        branchResult.put("pageNum",resultVO.getPage_num());

        return branchResult;
    }


    public String addFace(Integer customerId,
                          String faceUrl,
                          String appId){

        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        int score = FaceHelperV3.detectFace(shop.getId(), faceUrl);
        if (score < 70) {
            throw new ServiceException("人脸图片质量不合格");
        }

        String persionid = shop.getId() + "_" + customerId;

        Condition condition = new Condition(Face.class);
        condition.or().andEqualTo("customerId",customerId)
                    .andEqualTo("persionid", persionid);

        List<Face> faceList = faceRepository.findByCondition(condition);

        String faceID;

        if (faceList != null && faceList.size() > 0) {
            if (faceList.size() >= 5) {
                throw new ServiceException("单会员在此商店下最多存在5张图片");
            }
            for (Face face : faceList) {
                if (face.getFaceurl().equals(faceUrl)) {
                    throw new ServiceException("不可添加重复图片");
                }
            }
            faceID = FaceHelperV3.addFace(persionid,faceUrl);
        }else {
            faceID = FaceHelperV3.createPerson(String.valueOf(shop.getId()),
                    persionid, faceUrl);
        }

        if (faceID != null) {
            Face temp = new Face();
            temp.setFaceid(faceID);
            temp.setCustomerId(customerId);
            temp.setFaceurl(faceUrl);
            temp.setPersionid(persionid);
            faceRepository.save(temp);
            return faceID;
        }else {
            throw new ServiceException("添加人脸失败");
        }
    }

    public String replaceFace(Integer customerId,
                              String faceUrl,
                              String appId){

        Shop shop = appIdShopMap.get(appId);

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        int score = FaceHelperV3.detectFace(shop.getId(), faceUrl);
        if (score < 70) {
            throw new ServiceException("人脸图片质量不合格");
        }

        String persionid = shop.getId() + "_" + customerId;

        Condition condition = new Condition(Face.class);
        condition.or().andEqualTo("customerId",customerId)
                .andEqualTo("persionid", persionid);

        List<Face> faceList = faceRepository.findByCondition(condition);

        String faceID;

        if (faceList != null && faceList.size() > 0) {
            if (FaceHelperV3.deletePerson(persionid)) {
                faceRepository.deleteByCondition(condition);
            }else {
                throw new ServiceException("替换人脸失败");
            }
        }

        faceID = FaceHelperV3.createPerson(String.valueOf(shop.getId()),
                    persionid, faceUrl);

        if (faceID != null) {
            Face temp = new Face();
            temp.setFaceid(faceID);
            temp.setCustomerId(customerId);
            temp.setFaceurl(faceUrl);
            temp.setPersionid(persionid);
            faceRepository.save(temp);
            return faceID;
        }else {
            throw new ServiceException("添加人脸失败");
        }
    }

    public JSONObject checkChannelShop(String phone,
                                       ShopChannel shopChannel){

        JSONObject result = shopService.checkChannelShop(phone,shopChannel);

        return result;
    }

    public JSONObject zhaoHangUpDate(ApiRegisterForm form){

        Shop shop = appIdShopMap.get(form.getAppId());

        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }

        //JSONObject result = customerService.zhaoHangUpDate(form,shop);

        return null;
    }



    public Integer updateOrAddConfig(ApiConfigForm form){
        Shop shop = appIdShopMap.get(form.getAppId());
        if (shop != null && (shop.getStatus() == 0 || shop.getStatus() == 3)) {
            LoggerUtil.console.info("shop info:{}", shop.getName());
        } else {
            throw new ServiceException("商户状态异常");
        }
        NormalConfig normalConfig = normalConfigMapper.selectByShopIdAndType(shop.getId());
        String name = "的url前缀";
        int flag = 0;
        try{
            if(normalConfig == null){
                normalConfig = new NormalConfig();
                normalConfig.setId(0);
                normalConfig.setShopId(shop.getId());
                normalConfig.setValue(form.getUrl());
                normalConfig.setName("满客宝商户号"+shop.getId()+name);
                flag = normalConfigMapper.insertSelective(normalConfig);
            }else{
                normalConfig.setValue(form.getUrl());
                flag = normalConfigMapper.updateByPrimaryKeySelective(normalConfig);
            }
        }catch(Exception e){
            logger.info(e.getMessage());
            return 10020;
        }
        if(flag > 0){
            return ErrorCode.SUCCESS.getCode();
        }else{
            return 10020;
        }
    }



}
